import { NextRequest, NextResponse } from 'next/server';
import { auth } from '@/lib/auth';
import { db } from '@/lib/db';
import { errorHandler } from '@/lib/error-handler';

// 获取项目所有文档
export async function GET(
  request: NextRequest, 
  { params }: { params: { id: string } }
) {
  try {
    const session = await auth();
    
    if (!session?.user) {
      return new NextResponse(JSON.stringify({ error: '未授权访问' }), { 
        status: 401, 
        headers: { 'Content-Type': 'application/json' } 
      });
    }
    
    const projectId = params.id;
    
    // 检查权限
    const projectMember = await db.projectUser.findFirst({
      where: {
        projectId,
        userId: session.user.id,
      }
    });
    
    if (!projectMember) {
      return new NextResponse(JSON.stringify({ error: '无权访问此项目' }), { 
        status: 403, 
        headers: { 'Content-Type': 'application/json' } 
      });
    }
    
    // 获取项目所有文档
    const documents = await db.document.findMany({
      where: {
        projectId,
      },
      orderBy: {
        updatedAt: 'desc'
      }
    });
    
    return NextResponse.json(documents);
    
  } catch (error) {
    return errorHandler(error);
  }
}

// 创建文档
export async function POST(
  request: NextRequest, 
  { params }: { params: { id: string } }
) {
  try {
    const session = await auth();
    
    if (!session?.user) {
      return new NextResponse(JSON.stringify({ error: '未授权访问' }), { 
        status: 401, 
        headers: { 'Content-Type': 'application/json' } 
      });
    }
    
    const projectId = params.id;
    
    // 检查项目成员权限
    const projectMember = await db.projectUser.findFirst({
      where: {
        projectId,
        userId: session.user.id,
      }
    });
    
    if (!projectMember || !['OWNER', 'ADMIN', 'EDITOR'].includes(projectMember.role)) {
      return new NextResponse(JSON.stringify({ error: '无权在此项目中创建文档' }), { 
        status: 403, 
        headers: { 'Content-Type': 'application/json' } 
      });
    }
    
    const body = await request.json();
    const { title, content = {} } = body;
    
    if (!title) {
      return new NextResponse(JSON.stringify({ error: '文档标题不能为空' }), { 
        status: 400, 
        headers: { 'Content-Type': 'application/json' } 
      });
    }
    
    // 创建文档
    const newDocument = await db.document.create({
      data: {
        title,
        content: content,
        projectId,
        version: 1,
        createdById: session.user.id,
        updatedById: session.user.id
      }
    });
    
    // 创建初始版本
    await db.documentRevision.create({
      data: {
        documentId: newDocument.id,
        content: content,
        version: 1,
        createdById: session.user.id
      }
    });
    
    return NextResponse.json(newDocument);
    
  } catch (error) {
    return errorHandler(error);
  }
} 